package com.example.dailyrecord.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.dailyrecord.entity.Token;
import lombok.Data;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;

@Data
@Component
@ConfigurationProperties(prefix = "auth.jwt")
public class TokenUtils {
    private String isuser;
    private String secret;
    private String header;
    private int expire;
    private Algorithm ALGORITHM;
    private String data;

    @PostConstruct
    private void preSet() {
        ALGORITHM = Algorithm.HMAC384(secret);
    }

    public String create(String email) {
        Date now = new Date();
        Date sevenDaysAfter = DateUtils.addDays(now, expire);
        return JWT.create().withIssuer(isuser)
                .withIssuedAt(now)
                .withExpiresAt(sevenDaysAfter)
                .withClaim(data, email)
                .sign(ALGORITHM);
    }

    public Token parse(String content) {
        String s ;
        try {
            DecodedJWT verify = JWT.require(ALGORITHM)
                    .withIssuer(isuser)
                    .build()
                    .verify(content);
            boolean expire = verify.getExpiresAt().before(new Date());
            if (expire) {
                return Token.getExpire(content);
            }
            s = verify.getClaim(data).asString();
        } catch (Exception e) {
            return Token.getError(content);
        }
        return Token.getSuccess(content, s);
    }
}
